﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO.IsolatedStorage;
using Newtonsoft.Json;

namespace Douban.View
{
    public partial class Login : PhoneApplicationPage
    {
        string accessStrings = "";
        IsolatedStorageSettings TokenSettings = IsolatedStorageSettings.ApplicationSettings;

        public Login()
        {
            InitializeComponent();
            this.Loaded += Login_Loaded;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Login_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (IsAuthorized())
                {
                    JumpToMainPage();
                }
                else
                {
                    OAuthStep1();
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void OAuthStep1()
        {
            string Url = App.OauthViewModel.AuthEntity.authPageUrl + "client_id=" + App.OauthViewModel.AuthEntity.client_id + "&redirect_uri=" + App.OauthViewModel.AuthEntity.redirect_uri + "&response_type=" + App.OauthViewModel.AuthEntity.response_type;

            webBrowser.Navigate(new Uri(Url));
            webBrowser.Navigated += webBrowser_Navigated;

        }

        void webBrowser_Navigated(object sender, NavigationEventArgs e)
        {
            if (e.Uri.ToString().Contains("back"))
            {
                if (e.Uri.ToString().Split('=')[1] == "access_denied")
                {
                }

            }
            else if (e.Uri.ToString().Contains("code="))
            {
                App.OauthViewModel.AuthEntity.authorization_code = e.Uri.ToString().Split('=')[1];
                OAuthStep2();
            }
            else if (e.Uri.ToString().Contains("token?"))
            {
                accessStrings = webBrowser.SaveToString();
                int nStart = accessStrings.IndexOf('{');
                int nEnd = accessStrings.IndexOf('}');
                accessStrings = accessStrings.Substring(nStart, nEnd - nStart + 1);

                OAuth.DoubanAuthEntity access = JsonConvert.DeserializeObject<OAuth.DoubanAuthEntity>(accessStrings);
                App.OauthViewModel.AuthEntity.access_token = access.access_token;
                App.OauthViewModel.AuthEntity.expires_in = access.expires_in;
                App.OauthViewModel.AuthEntity.refresh_token = access.refresh_token;
                App.OauthViewModel.AuthEntity.douban_user_id = access.douban_user_id;


                TokenSettings["access_token"] = access.access_token;
                TokenSettings["expires_in"] = DateTime.Now.AddSeconds(Convert.ToDouble(access.expires_in));
                TokenSettings["douban_user_id"] = access.douban_user_id;
                TokenSettings["refresh_token"] = access.refresh_token;

                JumpToMainPage();
            }

            //throw new NotImplementedException();
        }

        private void OAuthStep2()
        {
            string paras = "client_id=" + App.OauthViewModel.AuthEntity.client_id + "&client_secret=" + App.OauthViewModel.AuthEntity.client_secret + "&redirect_uri=" + App.OauthViewModel.AuthEntity.redirect_uri + "&grant_type=" + App.OauthViewModel.AuthEntity.grant_type + "&code=" + App.OauthViewModel.AuthEntity.authorization_code;

            byte[] header = System.Text.Encoding.UTF8.GetBytes(paras);
            string Addtionalheader = "Content-Type: application/x-www-form-urlencoded";
            webBrowser.Navigate(new Uri(App.OauthViewModel.AuthEntity.accessUrl), header, Addtionalheader);
        }


        /// <summary>
        /// return if has authentication
        /// </summary>
        /// <returns></returns>
        private bool IsAuthorized()
        {
            if (TokenSettings.Contains("access_token"))
            {
                if (Convert.ToDateTime(TokenSettings["expires_in"]).CompareTo(DateTime.Now) > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }

            return false;
        }

        /// <summary>
        /// jump to mainpage
        /// </summary>
        private void JumpToMainPage()
        {
            try
            {
                NavigationService.Navigate(new Uri(@"/View/MainPage.xaml", UriKind.RelativeOrAbsolute));
            }
            catch (System.NullReferenceException ex)
            {
                MessageBox.Show(ex.Message);
            }


        }
    }
}